package com.atguigu.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {

    public static void main(String[] args) throws IOException {

        new Thread() {
            public void run() {
                try {
                    SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));

//        F://terraria.v1.4.1.2.zip   F://mclc.zip
                    FileChannel fileChannel = new FileInputStream("F://terraria.v1.4.1.2.zip").getChannel();
                    long startTime = System.currentTimeMillis();

                    // 在linux下一个transferTo方法就可以完成
                    // 在windows下一次调用transferTo只能发送8M，就需要分段传输文件，而且要注意传输的位置
                    // transferTo底层使用零拷贝
//        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

                    long transferCount = 0;
                    long readPosition = 0;
                    long sectionLength = 1024 * 1024 * 8;
                    long totalTransferCount = 0;
                    while (readPosition < fileChannel.size()) {
                        transferCount = fileChannel.transferTo(readPosition, sectionLength, socketChannel);
                        readPosition += sectionLength;
                        totalTransferCount += transferCount;
                    }
                    if (transferCount == -1) {
                        fileChannel.close();
                    }
                    System.out.println("发送的总字节数：" + totalTransferCount + "，耗时：" + (System.currentTimeMillis() - startTime));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }
}
